import React, { useState, useEffect, useRef } from 'react'
import { Table, Button, Modal, Switch } from 'antd'
import axios from 'axios'
import { DeleteOutlined, EditOutlined, ExclamationCircleOutlined } from '@ant-design/icons'
import UserForm from '../../../components/user-manage/UserForm'
const { confirm } = Modal;
export default function UserList() {

    const [dataSource, setdataSource] = useState([])
    const [isAddVisible, setIsAddVisible] = useState(false);
    const [roleList, setRoleList] = useState([])
    const [regionList, setRegionList] = useState([])
    const [isUpdateVisible, setIsUpdateVisible] = useState(false);
    const [isUpdateDisabled, setIsUpdateDisabled] = useState(false);
    const [current, setCurrent] = useState(null)
    const {roleId,region,username,id}=JSON.parse(localStorage.getItem("token"))
    const addForm = useRef(null)
    const updateForm = useRef(null)
    
    useEffect(() => {
        axios.get("/regions").then(res => {
            setRegionList(res.data)
        })
    }, [])
    useEffect(() => {
        const roleObj={
            "1":"superadmin",
            "2":"admin",
            "3":"editor"
        }
        axios.get("/users?_expand=role").then(res => {
            const list=res.data
            
            setdataSource(roleObj[roleId]==="superadmin"?list:[
                ...list.filter(item=>item.username===username),
                ...list.filter(item=>item.region===region&&roleObj[item.roleId]==="editor")
            ])
        })
    }, [roleId,region,username])
    useEffect(() => {
        axios.get("/roles").then(res => {
            setRoleList(res.data)
        })
    }, [])
    const columns = [
        {
            title: '区域',
            dataIndex: 'region',
            filters:[
                ...regionList.map(item=>({
                    text:item.title,
                    value:item.value
                    
                })),
                {
                    text:"全球",
                    value:"全球"
                }
            ],
            onFilter: (value, item) => {
                if(item.region===""&&value==="全球"){
                   return true
                }
                else{
                    return  item.region===value
                }
            },
            render: (region) => {
                return (<b>{region === "" ? "全球" : region}</b>)
            }

        },
        {
            title: '角色名称',
            dataIndex: 'role',
            render: (role) => {
                return role?.roleName

            }
        },
        {
            title: '用户名',
            dataIndex: 'username',


        },
        {
            title: '用户状态',
            dataIndex: 'roleState',
            render: (roleState, item) => {
                return <Switch checked={roleState} disabled={item.default} onChange={() => handleChange(item)}></Switch>
            }

        },
        {
            title: '操作',

            render: (item) => {
                return (
                    <div>

                        <Button type="primary" shape="circle" icon={<EditOutlined />} onClick={() => {
                            handleUpdate(item)
                        }} />

                        <Button danger shape="circle" icon={<DeleteOutlined />} onClick={() => confirmMethod(item)}  disabled={checkUserDisabled(item)}/>
                    </div>
                )
            }

        },
    ];
    const checkUserDisabled=(item)=>{
        if(item.id===id){
            return true
        }
        else{
           return false
        }

    }
    const handleUpdate = (item) => {
        setTimeout(() => {
            setIsUpdateVisible(true)
            if (item.roleId === 1) {
                setIsUpdateDisabled(true)
            }
            else {
                setIsUpdateDisabled(false)
            }
            updateForm.current.setFieldsValue(item)
        }, 0)
        setCurrent(item)
    }

    const handleChange = (item) => {
        item.roleState = !item.roleState
        setdataSource([...dataSource])
        axios.patch(`/users/${item.id}`, { roleState: item.roleState })
    }

    const confirmMethod = (item) => {
        confirm({
            title: '确定要删除吗?',
            icon: <ExclamationCircleOutlined />,

            onOk() {
                deleteMethod(item)
            },
            onCancel() {

            },
        });

    }
    const deleteMethod = (item) => {
        //当前页面同步+后端数据同步删除
        setdataSource(dataSource.filter(data => data.id !== item.id))
        axios.delete(`/users/${item.id}`)
    }
    const addFormOk = () => {

        addForm.current.validateFields().then(value => {
            setIsAddVisible(false)
            addForm.current.resetFields()
            axios.post(`/users`, {
                ...value,
                "roleState": true,
                "default": false,
            }).then(res => {
                setdataSource([...dataSource, {
                    ...res.data,
                    role: roleList.filter(item => item.id === value.roleId)[0]
                }])
            })
        }).catch(err => {
            console.log(err)
        })

    }
    const updateFormOk = () => {
        updateForm.current.validateFields().then(value => {
           
            setIsUpdateVisible(false)
            setdataSource(dataSource.map(item => {
                
               
                if (item.id === current.id) {
                    return {
                        ...item,
                        ...value,
                        role: roleList.filter(data => data.id === value.roleId)[0]
                    }
                    
                }
                else {
                    return item
                }
            }))
            setIsUpdateDisabled(!isUpdateDisabled)

            axios.patch(`/users/${current.id}`,
                value,
                
            )
           


        }).catch(err => {
            console.log(err)
        })

    }

    return (
        <div>
            <Button type="primary" onClick={() => { setIsAddVisible(true) }}>添加用户</Button>
            <Table dataSource={dataSource} columns={columns} rowKey={(item) => item.id} pagination={{
                pageSize: 5
            }}
            />
            <Modal
                visible={isAddVisible}
                title="添加用户"
                okText="确定"
                cancelText="取消"
                onCancel={() => { setIsAddVisible(false) }}
                onOk={() => addFormOk()}
            >
                <UserForm regionList={regionList} roleList={roleList} ref={addForm}></UserForm>

            </Modal>
            <Modal
                visible={isUpdateVisible}
                title="更新用户"
                okText="更新"
                cancelText="取消"
                onCancel={() => {
                    setIsUpdateVisible(false)
                    setIsUpdateDisabled(!isUpdateDisabled)
                }}
                onOk={() => updateFormOk()}
            >
                <UserForm regionList={regionList} 
                roleList={roleList} 
                ref={updateForm} 
                isUpdateDisabled={isUpdateDisabled}
                isUpdate={true}
                ></UserForm>

            </Modal>
        </div>
    )

}
